package main;

import main.exceptions.ElementException;

%%

%cup
%line
%column
%unicode
%class MagicLexer


%{

	private Integer currentElement;
	private Integer base1 = null;
	private Integer base2 = null;
	
	private void addCombination() throws ElementException {
		Main.addCombination(currentElement, base1, base2);
		this.base1 = null;
		this.base2 = null;
	}
%}

%s ELEMENT1
%s ELEMENT2
%s TRAP

NEWLINE = \r|\n|\r\n
SPACE = [ \t\f]
WHITESPACE = {SPACE} | {NEWLINE}
NUMBER = [1-9][0-9]*
COLON = ":"
COMMA = ","
ANY = (. | NEWLINE)*

ELEMENT = {NUMBER}
PREFIX = {ELEMENT}{COLON}
COMBINATION = {ELEMENT}{SPACE}+{ELEMENT}
EMPTY_PRODUCTION = {PREFIX}{WHITESPACE}*
PRODUCTION = {PREFIX}({SPACE}*{COMBINATION}{SPACE}*{COMMA})*{SPACE}*{COMBINATION}{WHITESPACE}*

%%

{EMPTY_PRODUCTION} {
	/* Ignore empty productions */
}

{PRODUCTION} {
	this.currentElement = Integer.valueOf(yytext().split(":")[0].trim());
	String combinations = yytext().substring(yytext().indexOf(":") + 1);
	String combinationsArray[] = combinations.split(",");
	for(String combination : combinationsArray) {
		String div[] = combination.trim().split(" ");
		this.base1 = Integer.valueOf(div[0].trim());
		this.base2 = Integer.valueOf(div[1].trim());
		try {
			addCombination();	
		}catch(Exception e) {
			System.out.println("Error: Elemento inexistente.(Fila: " + (yyline + 1) + " Columna: " + (yycolumn + 1) + ")");
		}
	}
}

. {
	System.out.println("Error: Archivo mal formado.(Fila: " + (yyline + 1) + " Columna: " + (yycolumn + 1) + ")");
	yybegin(TRAP);
}

<TRAP> {ANY} {
}